package com.xbh.boot_study.util;

import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

@Component
public class ValidUtil {

    public static Validator validator;

    /**
     * validator在spring中已被管理
     */
    @Autowired
    public void setValidator(Validator validator) {
        ValidUtil.validator = validator;
    }

    /**
     * 分组校验
     */
    public static <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {

        return validator.validate(object, groups);
    }


    /**
     * 默认会校验完所有字段,然后才抛出异常。可通过配置,一旦校验失败就立即返回
     */
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                // 快速失败配置：true 快速失败返回模式 false 普通模式
                // .failFast(true)
                // hibernate.validator.fail_fast：true 快速失败返回模式 false 普通模式
                .addProperty( "hibernate.validator.fail_fast", "true" )
                .buildValidatorFactory();

        return validatorFactory.getValidator();
    }


}
